package com.hb.trans.di

import android.app.Application
import com.base.di.ActivityScope
import com.basiclib.lifecycle.ActivityLifecycleForRxLifecycle
import com.basiclib.lifecycle.FragmentLifecycleForRxLifecycle
import com.basiclib.network.HttpService
import com.basiclib.network.ResponseErrorListener
import com.basiclib.network.RxErrorHandler
import com.ctcnit.templatepro.global.HeaderInterceptor
import com.hb.trans.api.EndPoints
import com.hb.trans.bean.NetWork
import com.hb.trans.global.HbApplication
import com.hb.trans.global.IS_RELEASE
import com.hb.trans.global.ResponseErrorListenerImpl
import dagger.Module
import dagger.Provides
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import javax.inject.Singleton

@Module
class AppModules {

    @Singleton
    @Provides
    fun provideNetWork() = NetWork(IS_RELEASE)

    @Singleton
    @Provides
    fun provideRetrofit(netWork: NetWork): Retrofit {
        val logger = HttpLoggingInterceptor().apply {
            level = if (netWork.isRelease) HttpLoggingInterceptor.Level.NONE else HttpLoggingInterceptor.Level.BODY
        }
        val headerInterceptor = HeaderInterceptor()
        return HttpService.Builder(netWork.baseUrl, logger, headerInterceptor).build()
    }

    @Provides
    @Singleton
    fun provideEndPoint(retrofit: Retrofit) = retrofit.create(EndPoints::class.java)

    @Provides
    @Singleton
    fun provideFragmentLifecycleRxLifecycle() = FragmentLifecycleForRxLifecycle()

    @Provides
    @Singleton
    fun provideActivityLifecycleForRxLifecycle(fragmentLifecycleForRxLifecycle: FragmentLifecycleForRxLifecycle): Application.ActivityLifecycleCallbacks =
        ActivityLifecycleForRxLifecycle(fragmentLifecycleForRxLifecycle)

    /**
     * 提供处理 RxJava 错误的管理器
     *
     * @param application
     * @param listener
     * @return [RxErrorHandler]
     */
    @Singleton
    @Provides
    internal fun provideRxErrorHandler(application: Application, listener: ResponseErrorListener): RxErrorHandler {
        return RxErrorHandler
            .builder()
            .with(application)
            .responseErrorListener(listener)
            .build()
    }

    /**
     * 提供处理 RxJava 错误的管理器的回调
     *
     * @return
     */
    @Singleton
    @Provides
    internal fun provideResponseErrorListener(): ResponseErrorListener {
        return ResponseErrorListenerImpl()
    }
}

@Module
class EndpointModule {
    @Provides
    @ActivityScope
    fun provideEndpoint() = HbApplication.appComponent.endpoints()
}

@Module
class MainActivityModule {
}